import os
import sys
import shutil
import traceback
from mcp import StdioServerParameters, ClientSession
from mcp.client.stdio import stdio_client
from langchain_mcp_adapters.tools import load_mcp_tools
import asyncio
from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI
from pydantic import SecretStr

llm = ChatOpenAI(
    model_name="qwen3-max",
    temperature=0,
    openai_api_key=SecretStr(os.getenv("OPENAI_API_KEY", "sk-REPLACE")),
    openai_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1",
    streaming=True,
)

async def create_mcp_playwright_client():
    # 确保 npx 可用（Windows 可能需要 npx.cmd）
    npx_exec = shutil.which("npx") or shutil.which("npx.cmd")
    if not npx_exec:
        raise RuntimeError("找不到 npx，可执行文件未在 PATH 中。请安装 Node.js/npm 或把 npx 加入 PATH。")

    server_params = StdioServerParameters(
        command=npx_exec,
        args=["-y", "@executeautomation/playwright-mcp-server"],
    )

    try:
        async with stdio_client(server_params) as (read, write):
            async with ClientSession(read, write) as session:
                try:
                    await session.initialize()
                except Exception as e:
                    print("session.initialize() failed:")
                    traceback.print_exception(type(e), e, e.__traceback__)
                    raise

                try:
                    tools = await load_mcp_tools(session)
                    print("Loaded tools:", tools)
                except Exception as e:
                    print("load_mcp_tools failed:")
                    traceback.print_exception(type(e), e, e.__traceback__)
                    raise

    except ExceptionGroup as eg:  # Python 3.11+, catch grouped exceptions without except*
        print("Caught ExceptionGroup, inner exceptions:")
        for sub in eg.exceptions:
            traceback.print_exception(type(sub), sub, sub.__traceback__)
        raise
    except Exception as e:
        print("Caught exception:")
        traceback.print_exception(type(e), e, e.__traceback__)
        raise

if __name__ == "__main__":
    try:
        asyncio.run(create_mcp_playwright_client())
    except ExceptionGroup as eg:
        print("Top-level ExceptionGroup:")
        for sub in eg.exceptions:
            traceback.print_exception(type(sub), sub, sub.__traceback__)
        raise
    except Exception as e:
        print("Top-level single exception:")
        traceback.print_exception(type(e), e, e.__traceback__)
        raise